<template>
  <div class="note">
    <headerPhoto class="note-header">
      <div class="box">
        <i class="bi bi-stickies-fill"></i><span class="ms-2">风里笺</span>
      </div>
      <div class="my-text mt-2">风记，云随笔</div>
    </headerPhoto>
    <waveView></waveView>
    <div class="content">
      <ul>
        <li v-for="(item, index) in noteList" :key="index" class="mycard d-flex">
          <!-- 博主发表 -->
          <div class="left">
            <img src="../static/imgs/images/myUser.jpg" alt="">
          </div>
          <div class="right">
            <div>
              <div class="header">
                <div class="user">
                  <span class="name">君惜泪</span>
                  <span class="title rounded ms-2">巅峰</span>
                </div>
              </div>
              <div class="text">
                {{ item.note_text }}
              </div>
              <div class="box d-flex justify-content-between">
                <div class="time">
                  <span>{{ item.createAt || '未知时间' }}</span>
                </div>
                <div class="box-right">
                  <span>{{ noteCommentArr[index] ? noteCommentArr[index].length : '' }}</span>
                  <i @click="commentOpenFn(index)"
                    :class="['bi bi-chat-left-text', { 'active': commentOpen[index] }]"></i>
                  <i @click="writeOpenFn(index)" :class="['bi bi-pencil-square', { 'active': writeOpen[index] }]"></i>
                </div>
              </div>
            </div>
            <!-- 发表留言 -->
            <div v-if="writeOpen[index]" class="write">
              <div class="write-header">
                <i class="bi bi-pencil-square"></i>
                <span>评论</span>
              </div>
              <textarea v-model="text" placeholder="留下点什么..."></textarea>
              <div class="write-footer">
                <button @click="clickPublish(item.id, index)" class="btn text-light">提交</button>
              </div>
            </div>

            <!-- 留言列表 -->
            <div v-if="commentOpen[index]" class="comment">
              <div class="comment-header">
                <i class="bi bi-chat-left-text"></i>
                <span>{{ noteCommentArr[index] ? noteCommentArr[index].length : '' }}条留言</span>
              </div>

              <div v-for="(opt, i) in noteCommentArr[index]" :key="i" class="comment-content">
                <div class="comment-item">
                  <div class="left">
                    <!-- <img src="../static/imgs/images/morenuser.png" alt=""> -->
                    <img :src="opt?.imgUrl" alt="">
                  </div>
                  <div class="right">
                    <div class="header">
                      <div class="user">
                        <span class="name">{{ opt?.username }}</span>
                        <span class="title rounded ms-2">巅峰</span>
                      </div>
                    </div>
                    <div class="time">
                      <span>{{ opt?.createAt || '未知时间' }}</span>
                    </div>
                    <div class="text">
                      {{ opt?.comment }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </li>

        <div class="myBtn text-center">
          <button @click="nextNote" class="btn btn-sm btn-outline-warning border rounded-5">更多</button>
        </div>

        <!-- <div v-if="noteList.length < page_num * page_size" class="text-center message">
          到底啦~~~
        </div> -->
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import headerPhoto from '@/component/headerPhoto.vue';
import waveView from '@/component/waveView.vue';
import { getNoteList, getListByNote, formatDate, publishNoteCom, imgUrl } from "@/api/index"
import { ref } from 'vue';
import { useCounterStore } from "@/stores/counter"
import { ElMessage } from 'element-plus'
const counter = useCounterStore()
// 控制留言框按钮
const writeOpen = ref<{ [key: number]: boolean }>({})
// 控制评论区按钮
const commentOpen = ref<{ [key: number]: boolean }>({})
// 控制留言框
const writeOpenFn = (index: number) => {
  writeOpen.value[index] = !writeOpen.value[index]
  // console.log(writeOpen.value)
}

// 控制评论区
const commentOpenFn = (index: number) => {
  commentOpen.value[index] = !commentOpen.value[index]
  // console.log(commentOpen.value)
}

interface Inote {
  id: number;
  note_text: string;
  createAt: string;
}
// 随笔列表
const noteList = ref<Inote[]>([])

const page_num = ref<number>(1)
const page_size = ref<number>(5)

const noteId = ref<number[]>([])

interface noteItem {
  id: number;
  comment: string;
  createAt: string;
  username: string;
  note_id: number;
  user_id: number;
  imgUrl: string;
}
//  随笔评论列表
const noteCommentArr = ref<noteItem[][]>([])


// 评论
const text = ref<string>('')
// 点击发表
const clickPublish = (id: number, index: number) => {
  // console.log(comment.value)
  // console.log(id)
  const note_id = id
  const obj = counter.userData;
  // console.log(obj)
  const user_id = obj.id
  const imgUrl = obj.imgUrl;
  const username = obj.username
  const comment = text.value
  publishNoteComFn({ note_id, user_id, imgUrl, username, comment, index })
}
interface publishItem {
  note_id: number;
  user_id: number;
  imgUrl: string;
  username: string;
  comment: string;
  index: number;
}
// 发表评论
const publishNoteComFn = async ({ note_id, user_id, imgUrl, username, comment, index }: publishItem) => {
  const token = localStorage.getItem("TTOO")
  if (token) {
    const userStatus = await counter.loginedStatusFn(token)
    // console.log(userStatus)
    if (userStatus) {
      if (comment.trim() == '' || comment == null) {
        ElMessage({
          showClose: true,
          message: '你还没写呢~~',
          type: 'warning',
          offset: 100
        })
        return
      }
      await publishNoteCom({ note_id, user_id, imgUrl, username, comment }).then(
        async res => {
          console.log("发表评论", res.data)
          if (res.data.code == 200) {
            ElMessage({
              showClose: true,
              message: '发表成功~~',
              type: 'success',
              offset: 100,
              plain: true,
            })
            text.value = ''
            await getCommentFn()
            commentOpen.value[index] = true
          } else {
            ElMessage({
              showClose: true,
              message: res.data.msg,
              type: 'error',
              offset: 100,
              plain: true,
            })
            text.value = ''
          }
        },
        err => {
          console.log(err)
        }
      )
    } else {
      ElMessage({
        showClose: true,
        message: '登录状态已过期~~',
        type: 'error',
        offset: 100,
        plain: true,
      })
      return false
    }
  } else {
    ElMessage({
      showClose: true,
      message: '请先登录~~',
      type: 'error',
      offset: 100,
      plain: true,
    })
    return false
  }

}

// 获取随笔列表
const getNoteListFn = async () => {
  await getNoteList({ page_num: page_num.value, page_size: page_size.value })
    .then(
      res => {
        // console.log(res.data)
        if (res.data.code == 200) {
          noteList.value = res.data.result.map((item: Inote) => {
            item.createAt = formatDate(item.createAt)
            return item
          })
          noteId.value = res.data.result.map((item: Inote) => {
            return item.id
          })
          // console.log("随笔的id", noteId.value)
          getCommentFn()
        }
      },
      err => {
        console.log(err)
      }
    )
}
getNoteListFn()

const nextNote = () => {
  // 检查是否还有更多数据
  if (noteList.value.length < page_num.value * page_size.value) {
    ElMessage({
      showClose: true,
      message: '没有更多数据啦~~',
      type: 'warning',
      offset: 100,
      plain: true,
    })
  } else {
    page_size.value += 10;
    getNoteListFn();
  }

}
// 获取指定随笔评论列表
const getListByNoteFn = async (id: number) => {
  return await getListByNote({ note_id: id })
    .then(
      res => {
        // console.log("指定随笔评论列表", res)
        if (res.data.code == 200) {
          const arr = res.data.result.map((item: noteItem) => {
            item.imgUrl = imgUrl(item.imgUrl)
            item.createAt = formatDate(item.createAt)
            return item
          }).reverse();
          // console.log('指定随笔评论列表', arr)
          return arr
        } else {
          return []
        }

      },
      err => {
        console.log(err)
      }
    )
}

// 整理随笔评论列表
const getCommentFn = async () => {
  noteCommentArr.value = [];
  for (const id of noteId.value) {
    if (id !== undefined) {
      const arr = await getListByNoteFn(id); // 等待完成
      noteCommentArr.value.push(arr);
    }
  }
  // console.log('所有随笔评论列表', noteCommentArr.value);
};

</script>

<style lang="less" scoped>
.note {
  padding-bottom: 30px;
}

.note-header {
  background-color: #737070;


  .box {
    i {
      color: #FFA500;
      font-size: 25px;
    }

    span {
      color: #fff;
      vertical-align: middle;
      font-size: 35px;
    }
  }

  .my-text {
    color: #fff;
    font-size: 20px;
  }
}

.content {
  width: 100%;
  // min-height: 700px;

  background: linear-gradient(90deg, rgba(60, 10, 30, .05) 5%, #fff 0), linear-gradient(1turn, rgba(60, 10, 30, .05) 5%, #fff 0);
  background-size: 30px 30px;

  ul {
    transform: translateY(-45px);
    // margin-top: 30px;
    width: 50%;
    margin: 0 auto;
    padding: 20px 15px 10px;
    border-radius: 15px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
    animation: move 1s ease-in-out;
    background-color: #fff;

    // height: 700px;
    li {
      width: 100%;
      // background-color: red;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f0f0f0;

      .left {
        width: 50px;

        img {
          width: 100%;
          border-radius: 10px;
        }
      }

      .right {
        width: calc(100% - 50px);
        padding-left: 10px;

        .header {
          .user {
            .name {
              color: #737070;
              vertical-align: middle;
            }

            .title {
              color: #FFA500;
              border: 1px solid #FFA500;
              vertical-align: middle;
              font-size: 10px;
              padding: 0 2px;
            }
          }
        }

        .time {
          font-size: 12px;
          color: #7d7b7b;
        }

        .text {
          margin: 10px 0;
        }

        .box-right {
          padding: 0 5px;
          border-radius: 5px;
          background-color: #f0f0f0;

          span {
            color: #7d7b7b;
            font-size: 12px;
            vertical-align: middle;
          }

          i {
            color: #7d7b7b;
            font-size: 12px;
            vertical-align: middle;
            cursor: pointer;
            margin-left: 5px;

            &.active {
              color: #FFA500;
            }

            &:hover {
              color: #FFA500;
            }
          }
        }

        .write {
          width: 100%;


          .write-header {
            color: #FFA500;
            margin: 10px 0;

            i {
              vertical-align: middle;
            }

            span {
              vertical-align: middle;
            }
          }

          textarea {
            width: 100%;
            height: 120px;
            padding: 5px;
            border-radius: 5px;
            outline: none;
            border: 1px solid #FFA500;
            font-size: 12px;
          }

          .write-footer {
            text-align: right;

            .btn {
              padding: 2px 10px !important;
              background-color: #837BC7;
            }
          }
        }

        .comment {
          width: 100%;

          .comment-header {
            color: #FFA500;
            font-size: 14px;

            span {
              margin-left: 5px;
            }
          }

          .comment-content {
            .comment-item {
              display: flex;
              margin: 10px 0;

              .right {
                .time {
                  margin-top: 5px;
                  font-size: 10px;
                }

                .text {
                  padding: 6px 10px;
                  background-color: #f0f0f0;
                  border-radius: 10px;
                  font-size: 12px;
                }
              }
            }
          }
        }
      }
    }
  }

  @media (max-width: 1030px) {
    ul {
      width: 70%;
    }
  }

  @media (max-width: 800px) {
    ul {
      width: 80%;
    }
  }

  @media(max-width: 600px) {
    ul {
      width: 100%;
    }
  }
}

@keyframes move {
  0% {
    transform: translateY(20%);
  }

  100% {
    transform: translateY(-45px);
  }
}
</style>
